package com.jbp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.dao.SkillUserDao;
import com.jbp.exception.RRException;
import com.jbp.model.*;
import com.jbp.redis.RedisConfigService;
import com.jbp.service.*;
import com.jbp.utils.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 用户技能(SkillUser)表服务实现类
 * @author cc
 * @since 2020-11-19 17:06:55
 */
@Service
public class SkillUserServiceImpl extends ServiceImpl<SkillUserDao, SkillUser> implements SkillUserService {
    @Autowired
    private SkillParamService skillParamService;
    @Autowired
    private SkillUserParamService skillUserParamService;
    @Autowired
    private SkillService skillService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisConfigService redisConfigService;
    @Autowired
    private SkillOrderService skillOrderService;
    @Autowired
    private SkillOrderCommentService skillOrderCommentService;
    @Autowired
    private UserLevelService userLevelService;
    //是否是大神
    @Override
    public boolean isGod(Integer userId) {
        SkillUser one = getOne(new QueryWrapper<SkillUser>()
                .eq("user_id", userId)
                .eq("status", 3)
        );
        return one!=null;
    }

    //申请技能
    @Override
    @Transactional
    public void apply(Integer userId, SkillApplyReq req) {
        //删掉之前的skill 和 skillParams
        skillUserParamService.remove(new QueryWrapper<SkillUserParam>().eq("user_id", userId)
                .eq("skill_id", req.getSkillId()));
        remove(new QueryWrapper<SkillUser>().eq("user_id", userId)
                .eq("skill_id", req.getSkillId()));

        //添加skillUser
        SkillUser skillUser = new SkillUser();
        skillUser.setSkillId(req.getSkillId());
        skillUser.setUserId(userId);
        skillUser.setStatus(2);
        save(skillUser);

        //添加skillUserParam
        List<SkillParam> skillParams = skillParamService.list(new QueryWrapper<SkillParam>()
                .eq("skill_id", req.getSkillId())
                .eq("status", 1)
                .orderByAsc("sort")
        );

        for (SkillParam skillParam : skillParams) {
            if (req.getParams().containsKey(skillParam.getName())) {
                SkillUserParam skillUserParam = new SkillUserParam();
                skillUserParam.setUserId(userId);
                skillUserParam.setSkillId(req.getSkillId());
                skillUserParam.setSkillUserId(skillUser.getId());
                skillUserParam.setParamId(skillParam.getId());
                skillUserParam.setParamName(skillParam.getName());
                skillUserParam.setParamValue(req.getParams().get(skillParam.getName()));
                skillUserParam.setSort(skillParam.getSort());
                skillUserParamService.save(skillUserParam);
            }
        }

    }


    //我的技能
    @Override
    public List<SkillUser> mySkills(Integer userId) {
        List<SkillUser> list = list(new QueryWrapper<SkillUser>()
                .eq("user_id", userId)
                .eq("status", 3)
        );
        for (SkillUser skillUser : list) {
            Skill skill = skillService.getById(skillUser.getSkillId());
            skillUser.setSkillName(skill.getName());
            skillUser.setSkillImage(skill.getImage());
            skillUser.setSkillPriceUnit(skill.getPriceUnit());

            SkillUserParam priceParam = skillUserParamService.getOne(new QueryWrapper<SkillUserParam>()
                    .eq("skill_user_id", skillUser.getId())
                    .eq("param_name", "接单价格")
            );
            if (priceParam!=null) {
                skillUser.setPrice(Integer.parseInt(priceParam.getParamValue()));
            }

            //语音介绍
            SkillUserParam voiceParam = skillUserParamService.getOne(new QueryWrapper<SkillUserParam>().eq("skill_id", skillUser.getSkillId())
                    .eq("param_name", "录制语音介绍")
                    .eq("user_id", skillUser.getUserId())
            );
            if (voiceParam!=null) {
                skillUser.setVoice(voiceParam.getParamValue());
            }

            //服务人数
            skillUser.setOrderCount(getOrderCount(skillUser.getId()));
            //评分
            skillUser.setAvaScore(getAvaScore(skillUser.getId()));
        }
        return list;
    }

    //平均分
    private BigDecimal getAvaScore(Integer skillUserId) {
        BigDecimal avaScore = getBaseMapper().getAvaScore(skillUserId);

        return avaScore == null ? BigDecimal.ZERO : avaScore.setScale(1, BigDecimal.ROUND_HALF_UP);
    }

    //服务人数
    private Integer getOrderCount(Integer skillUserId) {
        return skillOrderService.count(new QueryWrapper<SkillOrder>()
                .eq("skill_user_id", skillUserId)
                .eq("status", 4)
        );
    }

    @Transactional
    @Override
    public void editSkill(Integer userId, SkillApplyReq req) {
        //添加skillUserParam
        List<SkillParam> skillParams = skillParamService.list(new QueryWrapper<SkillParam>()
                .eq("skill_id", req.getSkillId())
                .eq("status", 1)
                .orderByAsc("sort")
        );

        SkillUser skillUser = getOne(new QueryWrapper<SkillUser>().eq("user_id", userId).eq("skill_id", req.getSkillId()));
        if (skillUser==null) {
            throw new RRException("不存在该技能");
        }
        for (SkillParam skillParam : skillParams) {
            if (req.getParams().containsKey(skillParam.getName())) {
                SkillUserParam skillUserParam = skillUserParamService.getOne(new QueryWrapper<SkillUserParam>().eq("user_id", userId)
                        .eq("param_id", skillParam.getId()));

                if (skillUserParam==null) {
                    skillUserParam = new SkillUserParam();
                }
                skillUserParam.setUserId(userId);
                skillUserParam.setSkillId(req.getSkillId());
                skillUserParam.setSkillUserId(skillUser.getId());
                skillUserParam.setParamId(skillParam.getId());
                skillUserParam.setParamName(skillParam.getName());
                skillUserParam.setParamValue(req.getParams().get(skillParam.getName()));
                skillUserParam.setSort(skillParam.getSort());
                skillUserParamService.saveOrUpdate(skillUserParam);
            }
        }
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<SkillUserParam> wrapper = new QueryWrapper<>();
        String skillId = (String) params.get("skillId");
        wrapper.eq("skill_id", skillId);
        wrapper.eq("param_name", "接单价格");
        for (Map.Entry<String, Object> entry : params.entrySet()) {

            if (!Arrays.asList("skillId", "sort", "sex","page","limit").contains(entry.getKey())) {
                System.out.println(entry.getKey()+":"+entry.getValue());
                wrapper.inSql("user_id", "SELECT user_id FROM skill_user_param WHERE param_name = '" + entry.getKey() + "' and param_value like '%" + entry.getValue() + "%' and skill_id=" + skillId);
            }
        }
        if (params.get("sex") != null && !params.get("sex").equals("")){
            wrapper.inSql("user_id", "SELECT id FROM `user` WHERE sex='"+params.get("sex")+"'");
        }

        if ("priceAsc".equals(params.get("sort"))){
            wrapper.orderByAsc("param_value");
        } else if ("priceDesc".equals(params.get("sort"))){
            wrapper.orderByDesc("param_value");
        }

        IPage<SkillUserParam> page = skillUserParamService.page(
                new Query<SkillUserParam>().getPage(params),
                wrapper
        );

        List<SkillUser> list = new ArrayList<>();
        for (SkillUserParam skillUserParam : page.getRecords()) {
            SkillUser skillUser = getById(skillUserParam.getSkillUserId());
            skillUser.setPrice(Integer.parseInt(skillUserParam.getParamValue()));
            Skill skill = skillService.getById(skillUser.getSkillId());
            skillUser.setSkillName(skill.getName());
            skillUser.setSkillImage(skill.getImage());
            skillUser.setSkillPriceUnit(skill.getPriceUnit());

            User user = userService.getById(skillUser.getUserId());
            skillUser.setUserName(user.getName());
            skillUser.setUserSex(user.getSex());
            skillUser.setUserLevel(user.getLevel());
            skillUser.setUserLevelOn(userLevelService.levelOn(user.getId()));
            skillUser.setUserHead(user.getImg());
            skillUser.setUserIsOnline(user.getIsOnline());
            Object object = redisConfigService.get(Constant.ROOM_PREFIX+user.getId());
            if (object == null) {
                skillUser.setUserIsOnline("offline");
            }

            //语音介绍
            SkillUserParam voiceParam = skillUserParamService.getOne(new QueryWrapper<SkillUserParam>().eq("skill_id", skillId)
                    .eq("param_name", "录制语音介绍")
                    .eq("user_id", skillUser.getUserId())
            );
            if (voiceParam!=null) {
                skillUser.setVoice(voiceParam.getParamValue());
            }
            list.add(skillUser);

            //服务人数
            skillUser.setOrderCount(getOrderCount(skillUser.getId()));
            //评分
            skillUser.setAvaScore(getAvaScore(skillUser.getId()));
        }

        return new PageUtils(list, (int)page.getTotal(),(int)page.getPages(), (int)page.getCurrent());
    }

    @Override
    public SkillUser info(Integer skillUserId, Integer userId) {
        SkillUser skillUser = getById(skillUserId);
        if (skillUser==null) {
            throw new RRException("参数错误");
        }

        Skill skill = skillService.getById(skillUser.getSkillId());
        skillUser.setSkillName(skill.getName());
        skillUser.setSkillImage(skill.getImage());
        skillUser.setSkillPriceUnit(skill.getPriceUnit());

        User user = userService.getById(skillUser.getUserId());

        user = userService.getUserInformation(userId, user);
        skillUser.setUserName(user.getName());
        skillUser.setUserSex(user.getSex());
        skillUser.setUserLevel(user.getLevel());
        skillUser.setUserLevelOn(userLevelService.levelOn(user.getId()));
        skillUser.setUserHead(user.getImg());
        skillUser.setUserIsOnline(user.getIsOnline());

        List<SkillParam> list =  skillParamService.editList(skillUser.getSkillId(), userId);
        skillUser.setParams(list);

        skillUser.setUser(user);
        skillUser.setPrice(getPrice(skillUser.getId()).intValue());
        return skillUser;
    }

    @Override
    public BigDecimal getPrice(Integer skill_user_id){
        SkillUserParam priceParam = skillUserParamService.getOne(new QueryWrapper<SkillUserParam>()
                .eq("skill_user_id", skill_user_id)
                .eq("param_name", "接单价格")
        );
        return  priceParam!=null ? BigDecimal.valueOf(Double.parseDouble(priceParam.getParamValue())): BigDecimal.ZERO;
    }

    @Override
    public PageUtils hotGods(Map<String, Object> params) {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.inSql("id", "SELECT DISTINCT(user_id) FROM skill_user WHERE status=3");
        wrapper.orderByAsc("RAND()");
        IPage<User> page = userService.page(
                new Query<User>().getPage(params),
                wrapper
        );
        List<SkillUser> list = new ArrayList<>();
        for (User user : page.getRecords()) {
            user.setPassword("");
            user.setSalt("");

            List<SkillUser> skillUsers = mySkills(user.getId());
            user.setSkills(skillUsers);
        }

        return new PageUtils(page);
    }
}